import { Controller, Post, Query } from '@nestjs/common';
import { CalculateBetService } from 'src/calculate-bet/calculate-bet.service';
import { LineService } from 'src/line/line.service';
import { PlanService } from 'src/plan/plan.service';
import { TowerPointService } from 'src/tower-point/tower-point.service';

@Controller('calculate')
export class CalculateController {
  constructor(
    private readonly towerPointServie: TowerPointService,
    private readonly planService: PlanService,
    private readonly lineService: LineService,
    private readonly calculateBetService: CalculateBetService,
  ) {}

  @Post()
  async calculate(@Query() args: Record<string, any>) {
    const { id, name, w, H, ziDaoxianNum, xiangNum } = args;

    await this.towerPointServie.createMany(+id);
    const towerPoints = await this.towerPointServie.findAll({ id });
    const maxX = Math.max(...towerPoints.map((item) => item.x));
    const maxY = Math.max(...towerPoints.map((item) => item.y));
    const minY = Math.min(...towerPoints.map((item) => item.y));

    // 更新line
    await this.lineService.update(+id, {
      maxX,
      maxY,
      minY,
    });

    const plan = await this.planService.create({
      lineId: +id,
      name,
      w: +w,
      H: +H,
      ziDaoxianNum: +ziDaoxianNum,
      xiangNum: +xiangNum,
    });

    await this.calculateBetService.createMany(args, plan.id);
    return plan;
  }
}
